package io.boot.modules.activiti.controller;

import io.boot.common.annotation.BaseData;
import io.boot.common.annotation.DataScope;
import io.boot.common.utils.DateUtils;
import io.boot.common.utils.PageUtils;
import io.boot.common.utils.R;
import io.boot.common.validator.ValidatorUtils;
import io.boot.modules.activiti.dto.Done;
import io.boot.modules.activiti.entity.ActLeaveEntity;
import io.boot.modules.activiti.service.ActLeaveService;
import io.boot.modules.sys.controller.AbstractController;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 请假流程
 *
 * @author kyson
 */
@RestController
@RequestMapping("activiti/leave")
public class ActLeaveController extends AbstractController {
    @Autowired
    private ActLeaveService actLeaveService;

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @DataScope
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = actLeaveService.queryPage(params,getUserId());
        return R.ok().put("page", page);
    }


    /**
     * 详情信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        ActLeaveEntity actLeaveEntity = actLeaveService.getById(id);
        List<HistoricTaskInstance> historicTaskInstanceList=historyService // 历史相关Service
                .createHistoricTaskInstanceQuery() // 创建历史任务实例查询
                .processInstanceId(actLeaveEntity.getInstanceId()) // 用流程实例id查询
//                .finished() // 查询已经完成的任务
                .list();
        List<Done> doneList=new ArrayList<>();
        for (HistoricTaskInstance hi:historicTaskInstanceList) {
            Done done=new Done();
            done.setId(hi.getId());
            done.setName(hi.getName());
            done.setCreateTime(DateUtils.format(hi.getCreateTime(),DateUtils.DATE_TIME_PATTERN));
            done.setEndTime(DateUtils.format(hi.getEndTime(),DateUtils.DATE_TIME_PATTERN));
            done.setInstanceId(hi.getProcessInstanceId());
            done.setUpName(hi.getAssignee());
            doneList.add(done);
        }

        return R.ok().put("actLeaveEntity", actLeaveEntity).put("historicTaskInstanceList",doneList);
    }


    /**
     * 查询当前部署过的流程(状态为激活状态下)
     */
    @GetMapping(value = "/getInstance")
    public R getInstance(){
        //.active() 为激活  suspended 挂起
        List<ProcessDefinition> ProcessDefinitionList=repositoryService.createProcessDefinitionQuery()
                .active().list();
        List<Map> list=new ArrayList<>();
        for (ProcessDefinition definition: ProcessDefinitionList) {
            Deployment deployment = repositoryService.createDeploymentQuery()
                    .deploymentId(definition.getDeploymentId())
                    .singleResult();
            list.add(new HashMap(){{put("key",definition.getKey());put("name",deployment.getName()+":"+definition.getVersion());}});
        }
        return R.ok().put("list", list);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @BaseData("save")
    public R save(@RequestBody ActLeaveEntity actLeaveEntity){
        Map<String,Object> maps=new HashMap<>();
        String num=actLeaveEntity.getTotalTime().substring(0,actLeaveEntity.getTotalTime().indexOf("天"));
        maps.put("num",num);
        maps.put("createBy",getUser().getUsername());
        //启动流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(actLeaveEntity.getType(),maps);
        //校验类型
        ValidatorUtils.validateEntity(actLeaveEntity);
        actLeaveEntity.setCreateTime(new Date());
        actLeaveEntity.setCreateBy(getUserId());
        actLeaveEntity.setInstanceId(processInstance.getId());
        actLeaveService.save(actLeaveEntity);
        // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @BaseData("update")
    public R update(@RequestBody ActLeaveEntity actLeaveEntity){
        //校验类型
        ValidatorUtils.validateEntity(actLeaveEntity);
        actLeaveService.updateById(actLeaveEntity);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        actLeaveService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }



    /**
     * 激活 挂起
     * @param params
     * @return
     */
    @PostMapping("/hangactive")
    public R hangactive(@RequestBody Map<String, Object> params) {
        if(params.get("type").toString().equals("true")){
            //激活
            runtimeService.activateProcessInstanceById(params.get("id").toString());
        }else{
            //挂起
            runtimeService.suspendProcessInstanceById(params.get("id").toString());
        }
        return R.ok();
    }







}
